package com.wan.thread.async;

import com.wan.thread.ExecutorManager;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * 异步动作，尝试函数流式写法
 * 待完善
 * 思考：每个流动作使用actor绑定线程是否更有好处？即一串动作放在同一个线程下队列里执行
 * 当前每个动作都会在不同线程
 * 参照：CompletableFuture
 */
public class AsyncExecutor {

    public static AsyncExecutor get(){
        return SingleHolder.ASYNC_EXECUTOR;
    }

    static class SingleHolder{
        public static final AsyncExecutor ASYNC_EXECUTOR = new AsyncExecutor();
    }

    private final ExecutorService executorService;


    private AsyncExecutor() {
        this.executorService = ExecutorManager.getExecutor(ExecutorManager.Type.ASYNC,ExecutorManager.DEFAULT_CONFIG);
    }

    public <R>AsyncResult<R> async(Callable<R> callable){
        Future<R> future = executorService.submit(callable);
        return new AsyncResult<>(future);
    }

    protected <P,R>AsyncResult<R> thenApply(AsyncNextTask<P,R> nextTask){
        return async(nextTask);
    }
}
